package com.atguigu.product.service.impl;

import com.atguigu.product.dao.AttrDao;
import com.atguigu.product.dao.AttrGroupDao;
import com.atguigu.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.product.entity.AttrEntity;
import com.atguigu.product.entity.AttrGroupEntity;
import com.atguigu.product.entity.CategoryEntity;
import com.atguigu.product.service.AttrAttrgroupRelationService;
import com.atguigu.product.service.AttrGroupService;
import com.atguigu.product.service.AttrService;
import com.atguigu.product.service.CategoryService;
import com.atguigu.product.vo.AttrCateVo;
import com.atguigu.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils PageAttrIdAndKey(Map<String, Object> params,Long attrId,String type) {
        String key=(String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?1:0);
        //            指定catId时，如果有查询条件(key),就进行查询，key可能是attr_group_id，也可能是attr_group_name包含的数据
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
//        不指定catId时查询全部
        if(attrId==0){
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params)
                    , queryWrapper);
            PageUtils pageUtils = new PageUtils(page);
//            这里返回给前端显示的数据需要进行多表查询
            List<AttrEntity> records = page.getRecords();
            List<AttrCateVo> voList = records.stream()
                    .map((attrEntity) -> {
                        AttrCateVo attrCateVo = new AttrCateVo();

                        BeanUtils.copyProperties(attrEntity, attrCateVo);
//                      查询所属分类
                        CategoryEntity category = categoryService.getById(attrEntity.getCatelogId());
                        if(category!=null){
                            attrCateVo.setCatelogName(category.getName());
                        }
//                      查询所属分组 ,如果是销售属性，则没有分组，只有基本属性有
                        if(attrEntity.getAttrType()==1){
                            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                            if(attrAttrgroupRelation!=null){
                                AttrGroupEntity attrGroup = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                                if(attrGroup!=null){
                                    attrCateVo.setGroupName(attrGroup.getAttrGroupName());
                                }
                            }
                        }
                        return attrCateVo;
                    }).collect(Collectors.toList());
            pageUtils.setList(voList);
            return pageUtils;
        }else {
            queryWrapper.eq("catelog_id",attrId);
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                    queryWrapper);
            PageUtils pageUtils = new PageUtils(page);
//            这里返回给前端显示的数据需要进行多表查询
            List<AttrEntity> records = page.getRecords();
            List<AttrCateVo> voList = records.stream()
                    .map((attrEntity) -> {
                        AttrCateVo attrCateVo = new AttrCateVo();

                        BeanUtils.copyProperties(attrEntity, attrCateVo);
//                      查询所属分类
                        CategoryEntity category = categoryService.getById(attrEntity.getCatelogId());
                        if(category!=null){
                            attrCateVo.setCatelogName(category.getName());
                        }
//                      查询所属分组 ,如果是销售属性，则没有分组，只有基本属性有
                        if(attrEntity.getAttrType()==1){
                            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                            if(attrAttrgroupRelation!=null){
                                AttrGroupEntity attrGroup = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                                if(attrGroup!=null){
                                    attrCateVo.setGroupName(attrGroup.getAttrGroupName());
                                }
                            }
                        }
                        return attrCateVo;
                    }).collect(Collectors.toList());
            pageUtils.setList(voList);
            return pageUtils;
        }
    }

    @Override
    public void saveAttrVo(AttrVo attrVo) {
//        先添加自己表中的
        AttrEntity attr=new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.save(attr);
//        再添加关联表中的 pms_attr_attrgroup_relation表 销售属性（attrtype=0）不需要添加
        if(attr.getAttrType()==1){
            AttrAttrgroupRelationEntity attrAttrgroupRelation=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attr.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelation);
        }

    }

    @Override
    public AttrCateVo getAttrAll(Long attrId) {
        AttrCateVo attrCateVo=new AttrCateVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrCateVo);
//        所属分组
        if(attrEntity.getAttrType()==1){
            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrAttrgroupRelation!=null){
                attrCateVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroup = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                if(attrGroup!=null){
                    attrCateVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
        }
//        所属分类
        Long[] allPath = categoryService.findAllPath(attrEntity.getCatelogId());
        attrCateVo.setCatelogPath(allPath);
        CategoryEntity category = categoryService.getById(attrEntity.getCatelogId());
        if(category!=null){
            attrCateVo.setCatelogName(category.getName());
        }
        return attrCateVo;
    }

    @Override
    public void updateAttr(AttrVo attrVo) {
//        先改变自己表中的数据
        AttrEntity attr=new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.updateById(attr);
//        再改变关联关系表中的数据 如果是销售属性就不需要
        if(attr.getAttrType()==1){
            AttrAttrgroupRelationEntity attrAttrgroupRelation=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attr.getAttrId());
//        查询关联表中有没有这个AttrId
            int count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
//        如果有，那么这是一个修改操作
            if(count>0){
                attrAttrgroupRelationService.update(
                        attrAttrgroupRelation,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())
                );
            }else{
//            如果没有，那么这是一个新增操作
                attrAttrgroupRelationService.save(attrAttrgroupRelation);
            }
        }
    }

    @Override
    public List<AttrEntity> groupIdGetAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream()
                .map((attr) -> {
                    return attr.getAttrId();
                }).collect(Collectors.toList());
        if(attrIds!=null&&attrIds.size()>0){
            Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;
        }else {
            return null;
        }
    }

    @Override
    public PageUtils groupIdGetNoAttr(Long attrgroupId,Map<String, Object> params) {
//        这个方法是找到自己能关联(属于同一个分类)但是还没有关联的属性
//        思路：
//          1、根据当前分组id获得当前分类id
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroup.getCatelogId();
//          2、根据当前分类id找到所有的分组id(包含自己)
        List<AttrGroupEntity> groupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
//        这里的这个集合attrGroupIds不用进行非空判断，因为一定会包含自己这个分组
        List<Long> attrGroupIds = groupEntityList.stream()
                .map((item) -> {
                    return item.getAttrGroupId();
                }).collect(Collectors.toList());
//            2.1）、这些分组的关联属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream()
                .map((item) -> {
                    return item.getAttrId();
                }).collect(Collectors.toList());
//            2.2）、从当前分类的所有属性中排除这些属性
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).notIn("attr_id", attrIds));
//          3、返回剩余的属性
        PageUtils pageUtils=new PageUtils(page);
        return pageUtils;
    }

}